package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

//自己编写一个函数，接收两个文件路径 srcFileName dstFileName

func copyFile(srcFileName string, dstFileName string) (err error) {
	byteStr, err1 := ioutil.ReadFile(srcFileName)
	if err1 != nil {
		return err1
	}

	err2 := ioutil.WriteFile(dstFileName, byteStr, 0666)
	if err2 != nil {
		return err2
	}
	return nil
}

// 自己编写一个函数，接收两个文件路径 srcFileName dstFileName
func copyFile2(srcFileName string, dstFileName string) (err error) {
	sFile, err1 := os.Open(srcFileName)
	defer sFile.Close() //必须关闭
	dFile, err2 := os.OpenFile(dstFileName, os.O_CREATE|os.O_WRONLY, 0666)
	defer dFile.Close() //必须关闭
	if err1 != nil {
		return err1
	}
	if err2 != nil {
		return err2
	}
	var tempSlice = make([]byte, 1280)
	for {
		//读取数据
		n1, err := sFile.Read(tempSlice)
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}
		// 写入数据
		if _, err := dFile.Write(tempSlice[:n1]); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	src := "./test.txt"
	dst := "./test1.txt"
	//err := copyFile(src, dst)
	err := copyFile2(src, dst)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("复制文件成功")
}
